<template>
  <div class="app-container">
    <h3>{{ isDetail ? '商品详情':'编辑商品' }}</h3>
    <el-form
      v-loading="loading"
      ref="goods"
      :rules="rules"
      :model="goods"
      :disabled="isDetail"
      label-width="150px"
    >
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="goods.goodsName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="goods.categoryId" placeholder="请选择">
          <el-option
            v-for="item in categoryList"
            :key="item.categoryId"
            :label="item.category"
            :value="item.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品图片" prop="goodsImageList">
        <pa-upload
          :action="action"
          :show-file-list="false"
          :file-list="goodsImageList"
          :limit="3"
          :headers="headers"
          :on-success="uploadPicUrl"
          :on-remove="onRemove"
          list-type="picture-card"
          class="avatar-uploader"
          accept=".jpg, .jpeg, .png, .gif"
        />
      </el-form-item>
      <el-form-item label="商品详情" prop="detailMobileHtml">
        <vue-ueditor-wrap
          v-model="goods.detailMobileHtml"
          :config="ueditorConfig.config"
          @ready="ueditorConfig.ready"
        />
      </el-form-item>

      <el-form-item label="商品价格" prop="price" placeholder="请输入">
        <el-input-number v-model="goods.price" :min="0" :precision="2" />
      </el-form-item>
      <el-form-item label="商品库存" prop="stock" placeholder="请输入">
        <el-input-number v-model="goods.stock" :min="1" />
      </el-form-item>
      <el-form-item label="商品状态" prop="publishStatus">
        <el-radio-group v-model="goods.publishStatus">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">仓库</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否推荐" prop="recommendStatus">
        <el-radio-group v-model="goods.recommendStatus">
          <el-radio :label="1">推荐</el-radio>
          <el-radio :label="0">不推荐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="关联课程" prop="courseId">
        <el-select v-model="goods.courseId" placeholder="请选择">
          <el-option
            v-for="item in courseList"
            :key="item.courseId"
            :label="item.courseName"
            :value="item.courseId"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="运费模版" prop="courseId">
        <el-select v-model="goods.templateId" placeholder="请选择">
          <el-option
            v-for="item in templateList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <div v-if="!isDetail" class="op-container">
        <el-button type="primary" @click="handlePublish('goods')">提交</el-button>
        <el-button @click="handleCancel('goods')">取消</el-button>
      </div>
    </el-form>
    <div v-if="isDetail" class="op-container">
      <el-button type="primary" @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  width: 145px;
  height: 145px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
.op-container {
  padding-left: 100px;
}
</style>

<script>
import ueditorConfig from '@/config/ueditorConfig'
import { listCategory } from '@/api/category'
import { getCourseList } from '@/api/course'
import { publishGoods, detailGoods, upGoods } from '@/api/goods'
// import { createStorage } from '@/api/storage'
import { getFreightList } from '@/api/freight/index'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import upload from '@/components/Upload'
export default {
  name: 'GoodsEdit',
  components: { Editor, 'pa-upload': upload },

  data() {
    var validImg = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请上传图片'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      ueditorConfig: ueditorConfig,
      action: `${process.env.BASE_API}/vms/v1/image/upload`,
      goodsImageList: [],
      goods: {
        goodsName: '',
        categoryId: '',
        detailMobileHtml: '',
        goodsImageList: [],
        price: '',
        publishStatus: 1,
        recommendStatus: 0,
        courseId: '',
        stock: '',
        templateId: ''
      },
      rules: {
        goodsName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ],
        detailMobileHtml: [
          { required: true, message: '商品详情不能为空', trigger: 'blur' }
        ],
        goodsImageList: [
          { required: true, validator: validImg, trigger: 'blur' }
        ],
        price: [
          { required: true, message: '商品价格不能为空', trigger: 'blur' }
        ],
        stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
      },
      categoryList: [],
      courseList: [],
      templateList: [],
      isDetail: false
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    },
    imgLength() {
      return this.goods.goodsImageList.length
    }
  },
  created() {
    this.getCategory()
    this.getCourseList()
    this.getTemplateList()
    const id = this.$route.query.id
    if (this.$route.query.isDetail) {
      this.isDetail = this.$route.query.isDetail
    }
    this.getDetail(id)
  },

  methods: {
    getTemplateList() {
      getFreightList({ index: 0, size: 100 })
        .then(response => {
          this.templateList = response.data.data.content
        })
        .catch(() => {
          this.categoryList = []
        })
    },
    getCategory() {
      listCategory({ index: 0, size: 100 })
        .then(response => {
          this.categoryList = response.data.data.content
        })
        .catch(() => {
          this.categoryList = []
        })
    },
    getCourseList() {
      getCourseList({ index: 0, size: 100 })
        .then(response => {
          this.courseList = response.data.data.content
        })
        .catch(() => {
          this.courseList = []
        })
    },

    handleCancel: function(formName) {
      this.$refs[formName].resetFields()
      this.$router.push({
        path: '/goods/list'
      })
    },
    handlePublish: function(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = this.goods
          this.loading = true
          // const reg = new RegExp(
          //   `<img src=`,
          //   'g',
          // )
          // params.detailMobileHtml = params.detailMobileHtml.replace(
          //   reg,
          //   `<img style="width:100%;height:auto;display:block" src=`,
          // )
          publishGoods(params)
            .then(res => {
              this.loading = false
              this.$notify.success({
                title: '成功',
                message: '编辑成功'
              })
              if (params.publishStatus === 1) {
                this.handleUp(res.data.data.id)
              } else {
                this.$router.push({ name: 'goodsList' })
              }
            })
            .catch(response => {
              this.loading = false
              MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                confirmButtonText: '确定',
                type: 'error'
              })
            })
        }
      })
    },
    uploadPicUrl: function(response) {
      this.$refs['goods'].clearValidate('goodsImageList')
      const length = this.goods.goodsImageList.length - 1
      this.goods.goodsImageList[length] = {
        name: response.name,
        url: response.data.fileUrl
      }
      // console.log(this.goods.goodsImageList)
      // this.goodsImageList = this.goods.goodsImageList
    },
    onRemove(file, fileList) {
      this.goods.goodsImageList.forEach((item, index) => {
        if (file.url === item.url) {
          this.goods.goodsImageList.splice(index, 1)
        }
      })
    },
    // 获取详情
    getDetail(id) {
      detailGoods(id).then(res => {
        const {
          id,
          goodsName,
          categoryId,
          courseId,
          detailMobileHtml,
          price,
          publishStatus,
          recommendStatus,
          goodsImageList,
          stock
        } = res.data.data
        this.goods.id = id
        this.goods.goodsName = goodsName
        this.goods.categoryId = categoryId
        this.goods.courseId = courseId
        this.goods.detailMobileHtml = detailMobileHtml
        this.goods.price = price
        this.goods.publishStatus = publishStatus
        this.goods.recommendStatus = recommendStatus
        this.goods.stock = stock
        this.goods.goodsImageList = goodsImageList.map(item => ({
          url: item.url
        }))
        this.goodsImageList = this.goods.goodsImageList
      })
    },
    goBack() {
      this.$router.go(-1)
    },
    handleUp(id) {
      upGoods(id)
        .then(res => {
          this.$router.push({ name: 'goodsList' })
        })
        .catch(error => {
          this.$message.error(error.data.respCode.message)
        })
    }
  }
}
</script>
